package org.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.util.JwtProperties;
import org.example.util.JwtUtil;
import org.example.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(jwtProperties.getUserTokenName());

        /**
         * 如果解析失败，说明token不合法，抛出异常，拦截器拦截，
         * 返回401状态码，前端收到401状态码，跳转到登录页
         */
        try {
            // 1、从redis中获取token
            String redisToken = (String) redisTemplate.opsForValue().get(token);
            // 2、判断是否为空，为空抛出异常
            if (redisToken == null) {
                throw new RuntimeException();
            }

            Map<String, Object> claims = jwtUtil.parseToken(token, jwtProperties.getUserSecretKey());

            // 将解析结果保存到ThreadLocal线程中
            ThreadLocalUtil.set(claims);

            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /**
         * 在请求处理完成后，移除ThreadLocal中的数据，避免内存泄露
         */
        ThreadLocalUtil.remove();
    }
}
